/**
 * 设备检测工具类
 */

// 检查是否是移动设备的用户代理关键词
const MOBILE_KEYWORDS = [
  'Android',
  'iPhone',
  'iPad',
  'iPod',
  'Windows Phone',
  'Mobile',
  'Tablet',
  'webOS',
  'BlackBerry',
  'Opera Mini'
]

/**
 * 通过 User Agent 判断是否为移动设备
 */
export function isMobileByUA(): boolean {
  const ua = navigator.userAgent
  return MOBILE_KEYWORDS.some(keyword => ua.includes(keyword))
}

/**
 * 通过屏幕触摸特性判断是否为移动设备
 */
export function isMobileByTouch(): boolean {
  return (
    'ontouchstart' in window ||
    navigator.maxTouchPoints > 0 ||
    // @ts-ignore
    navigator.msMaxTouchPoints > 0
  )
}

/**
 * 通过屏幕方向特性判断是否为移动设备
 */
export function isMobileByOrientation(): boolean {
  return typeof window.orientation !== 'undefined' ||
    navigator.userAgent.includes('IEMobile')
}

/**
 * 通过媒体查询判断是否为移动设备
 */
export function isMobileByMediaQuery(): boolean {
  return window.matchMedia('(max-width: 768px)').matches ||
    window.matchMedia('(hover: none) and (pointer: coarse)').matches
}

/**
 * 综合多个方法判断是否为移动设备
 * @param strict 是否采用严格模式（需要满足多个条件）
 */
export function isMobileDevice(strict = false): boolean {
  const checks = [
    isMobileByUA(),
    isMobileByTouch(),
    isMobileByOrientation(),
    isMobileByMediaQuery()
  ]

  if (strict) {
    // 严格模式：至少满足3个条件
    return checks.filter(Boolean).length >= 3
  }
  
  // 宽松模式：满足任意条件即可
  return checks.some(Boolean)
}

/**
 * 获取设备类型的详细信息
 */
export function getDeviceInfo() {
  const ua = navigator.userAgent
  const platform = navigator.platform
  const isIOS = /iPhone|iPad|iPod/.test(ua)
  const isAndroid = /Android/.test(ua)
  const isWechat = /MicroMessenger/.test(ua)
  const isAlipay = /AlipayClient/.test(ua)
  const isDingTalk = /DingTalk/.test(ua)
  const isWeibo = /Weibo/.test(ua)

  return {
    isIOS,
    isAndroid,
    isWechat,
    isAlipay,
    isDingTalk,
    isWeibo,
    isMobile: isMobileDevice(),
    platform,
    userAgent: ua
  }
}

// 监听设备方向变化
export function onOrientationChange(callback: (isPortrait: boolean) => void): () => void {
  const handler = () => {
    if (typeof window.orientation !== 'undefined') {
      // 使用 orientation
      callback(window.orientation === 0 || window.orientation === 180)
    } else {
      // 使用 matchMedia
      callback(window.matchMedia('(orientation: portrait)').matches)
    }
  }

  window.addEventListener('orientationchange', handler)
  // 同时监听 resize 事件作为备选
  window.addEventListener('resize', handler)

  // 返回清理函数
  return () => {
    window.removeEventListener('orientationchange', handler)
    window.removeEventListener('resize', handler)
  }
} 